'use strict'

const Service = require('egg').Service

class UserService extends Service {
  // 注册
  async register(params, type = 'formal') {
    const { ctx, app } = this
    // 游客注册 || 用户注册
    if (type === 'tourist') {
      const user = await app.model.User.findOne({ where: { ip: params.ip } })
      if (user) return user
      // 随机生成头像
      params.avatar = Math.floor(Math.random() * 14).toString()
      params.type = 2
      params.nickname = '游客'
      return app.model.User.create(params)
    } else {
      const user = await app.model.User.findOne({ where: { username: params.username } })
      if (user) ctx.throw(400, '用户名已存在')
      return app.model.User.create(params)
    }
  }
  // 根据用户id查找用户
  async findById(id) {
    return await this.app.model.User.findOne({
      where: {
        id
      },
      attributes: {
        exclude: ['password']
      }
    })
  }
  // 创建新token  user = {id:xx}
  async createNewToken(user) {
    const { ctx, app } = this
    // 生成访问token
    const accessToken = ctx.signAccessToken(user)
    // 生成刷新token
    const refreshToken = ctx.signRefreshToken(user)
    // redis
    const value = JSON.stringify({ accessToken, refreshToken })
    await app.redis.set(`user:${user.id}`, value, 'EX', 60 * 60 * 24 * 7)

    return accessToken
  }
}

module.exports = UserService
